<?php

namespace app\admin\controller\jy;

use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 案例管理
 * @icon fa fa-circle-o
 */
class Design extends Backend
{
    /**
     * Design模型对象
     * @var \app\admin\model\jy\Design
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jy\Design;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as &$row) {
                $row->visible(['id', 'design_name', 'cover_images', 'layout_ids', 'space_ids', 'style_ids', 'scan_count',
                    'scan_user_count', 'share_count', 'share_user_count', 'praise_count', 'praise_user_count',
                    'cover_to_url', 'weigh', 'status', 'create_time']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return string
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);
            // 参数校验
            if ($params['design_image'] == '[]') {
                $this->error(__('详情图不能为空'));
            }
            if (!$params['product_ids']) {
                $this->error(__('产品不能为空'));
            }
            Db::startTrans();
            try {
                $params['create_user'] = $this->auth->id;
                $params['layout_ids'] = $params['layout_ids'] ? ',' . trim($params['layout_ids'], ',') . ',' : '';
                $params['style_ids'] = $params['style_ids'] ? ',' . trim($params['style_ids'], ',') . ',' : '';
                $params['space_ids'] = $params['space_ids'] ? ',' . trim($params['space_ids'], ',') . ',' : '';
//                $params['color_ids'] = $params['color_ids'] ? ',' . trim($params['color_ids'], ',') . ',' : '';
                $result = $this->model->allowField(true)->save($params);
                if (!$result) {
                    Db::rollback();
                    $this->error(__('No rows were inserted'));
                }
                // 详情图
                $designImageList = json_decode($params['design_image'], true);
                foreach ($designImageList as $index => &$designImage) {
                    $designImage['weigh'] = $index;
                    $designImage['design_id'] = $this->model->id;
                    $designImage['create_user'] = $this->auth->id;
                }
                model('app\admin\model\jy\DesignImage')->saveAll($designImageList);
                // 产品配置
                $productIdList = explode(',', $params['product_ids']);
                if ($productIdList) {
                    foreach ($productIdList as $index => $item) {
                        $designProduct['product_id'] = $item;
                        $designProduct['design_id'] = $this->model->id;
                        $designProduct['create_user'] = $this->auth->id;
                        $designProductRet = \app\admin\model\jy\DesignProduct::get($designProduct);
                        if ($designProductRet) {
                            continue;
                        }
                        $ret = \app\admin\model\jy\DesignProduct::create($designProduct);
                        if ($ret === false) {
                            Db::rollback();
                            $this->error(__('No rows were inserted'));
                        }
                    }
                }
                Db::commit();
                $this->success();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->view->assign('designImageTpl', self::getDesignImageTpl());
        return $this->view->fetch();
    }

    /**
     * 编辑案例
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($ids = null)
    {
        $row = $this->model->alias('jd')
            ->field('jd.*, group_concat(DISTINCT jdp.product_id) productIds')
            ->join('jy_design_product jdp', 'jd.id = jdp.design_id', 'LEFT')
            ->where('jd.id', $ids)
            ->group('jd.id')
            ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 参数校验
                if ($params['design_image'] == '[]') {
                    $this->error(__('详情图不能为空'));
                }
                if (!$params['product_ids']) {
                    $this->error(__('产品不能为空'));
                }
                Db::startTrans();
                try {
                    $params['space_ids'] = $params['space_ids'] ? ',' . trim($params['space_ids'], ',') . ',' : '';
                    $params['layout_ids'] = $params['layout_ids'] ? ',' . trim($params['layout_ids'], ',') . ',' : '';
                    $params['style_ids'] = $params['style_ids'] ? ',' . trim($params['style_ids'], ',') . ',' : '';
//                    $params['color_ids'] = $params['color_ids'] ? ',' . trim($params['color_ids'], ',') . ',' : '';
                    $result = $row->allowField(true)->save($params);
                    if (!$result) {
                        Db::rollback();
                        $this->error(__('No rows were updated'));
                    }

                    $productIdList = explode(',', $params['product_ids']);
                    if ($productIdList) {
                        $productIdRet = model('\app\admin\model\jy\DesignProduct')
                            ->field('product_id')
                            ->whereIn('product_id', $ids)
                            ->select();
                        if ($productIdRet != $productIdList) {
                            // 删除关联关系表
                            model('\app\admin\model\jy\DesignProduct')
                                ->whereIn('design_id', $ids)
                                ->delete();
                            // 新增
                            foreach ($productIdList as $item) {
                                $designProduct['product_id'] = $item;
                                $designProduct['design_id'] = $ids;
                                $designProduct['create_user'] = $this->auth->id;
                                $ret = \app\admin\model\jy\DesignProduct::get($designProduct);
                                if ($ret) {
                                    continue;
                                }
                                $ret = \app\admin\model\jy\DesignProduct::create($designProduct);
                                if ($ret === false) {
                                    Db::rollback();
                                    $this->error(__('No rows were updated'));
                                }
                            }
                        }
                    }

                    // 图片
                    $designImageList = json_decode($params['design_image'], true);
                    foreach ($designImageList as $index => &$designImage) {
                        $designImage['weigh'] = $index;
                        $designImage['design_id'] = $row['id'];
                        $designImage['create_user'] = $this->auth->id;
                    }
                    model('\app\admin\model\jy\DesignImage')->where(['design_id' => $row['id']])->delete();
                    model('\app\admin\model\jy\DesignImage')->saveAll($designImageList);
                    Db::commit();
                    $this->success();
                } catch (ValidateException | Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['designImageJson'] = json_encode(
            model('\app\admin\model\jy\DesignImage')
                ->where(['design_id' => $row['id'], 'is_del' => 0])
                ->order('weigh', 'asc')->select());
        $this->view->assign('designImageTpl', self::getDesignImageTpl());
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     * @param string $ids
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                model('\app\admin\model\jy\DesignProduct')
                    ->whereIn('design_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\DesignImage')
                    ->whereIn('design_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\DesignPraise')
                    ->whereIn('design_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\DesignScan')
                    ->whereIn('design_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\DesignShare')
                    ->whereIn('design_id', $ids)
                    ->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function layout()
    {
        if ($this->request->isAjax()) {
            $searchValue = $this->request->post('searchValue');
            $list = [];
            $layoutList = Config::get('site.layout_list');
            $searchArr = false;
            if ($searchValue) {
                $searchArr = explode(",", trim($searchValue, ','));
            }
            foreach ($layoutList as $a => $k) {
                if ($searchArr !== false) {
                    if (in_array($a, $searchArr)) {
                        $list[] = ['id' => $a, 'name' => $k, 'pid' => 0];
                    }
                } else {
                    $list[] = ['id' => $a, 'name' => $k, 'pid' => 0];
                }
            }
            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function space()
    {
        if ($this->request->isAjax()) {
            $searchValue = $this->request->post('searchValue');
            $list = [];
            $layoutList = Config::get('site.space_list');
            $searchArr = false;
            if ($searchValue) {
                $searchArr = explode(",", trim($searchValue, ','));
            }
            foreach ($layoutList as $a => $k) {
                if ($searchArr !== false) {
                    if (in_array($a, $searchArr)) {
                        $list[] = ['id' => $a, 'name' => $k, 'pid' => 0];
                    }
                } else {
                    $list[] = ['id' => $a, 'name' => $k, 'pid' => 0];
                }
            }
            $result = array("total" => count($list), "list" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function style()
    {
        if ($this->request->isAjax()) {
            $searchValue = $this->request->post('searchValue');
            $list = [];
            $layoutList = Config::get('site.style_list');
            $searchArr = false;
            if ($searchValue) {
                $searchArr = explode(",", trim($searchValue, ','));
            }
            foreach ($layoutList as $a => $k) {
                if ($searchArr !== false) {
                    if (in_array($a, $searchArr)) {
                        $list[] = ['id' => $a, 'name' => $k, 'pid' => 0];
                    }
                } else {
                    $list[] = ['id' => $a, 'name' => $k, 'pid' => 0];
                }
            }
            $result = array("total" => count($list), "list" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取图片操作模板
     * @return string
     */
    private function getDesignImageTpl(): string
    {
        $inputStr = '<input id="c-item_title" data-rule="required" class="form-control name-input" name="<%=name%>[<%=index%>][item_title]" type="text" maxlength="20"
                   value="<%=row[\'item_title\']%>">';
        $uploadId = 'item_images_<%=index%>';
        $uploadName = '<%=name%>[<%=index%>][item_images]';
        $tpl = '<dd class="form-inline">'
            . $inputStr
            . '<input type="text" id="c-' . $uploadId . '" name="' . $uploadName . '" class="form-control" value="<%=row[\'item_images\']%>" size="25">'
            . '<div class="input-group-addon no-border no-padding form-control">'
            . '<span><button type="button" id="plupload-' . $uploadId . '" class="btn btn-danger plupload" data-input-id="c-' . $uploadId . '" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-' . $uploadId . '"><i class="fa fa-upload"></i>' . __('Upload') . '</button></span>'
            . '<span class="image-choose"><button type="button" id="fachoose-' . $uploadId . '" class="btn btn-primary fachoose" data-input-id="c-' . $uploadId . '" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i>' . __('Choose') . '</button></span>'
            . '</div>'
            . '<span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span>'
            . '<span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span>'
            . '<span class="msg-box n-right" for="c-' . $uploadName . '"></span>'
            . '<ul class="row list-inline plupload-preview" id="p-' . $uploadId . '"></ul>'
            . '</dd>';
        return $tpl;
    }
}
